package com.fourth.controller.api;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.fourth.config.RabbitConfiguration;
import com.fourth.rabbit.MsgProducer;
import com.fourth.service.*;
import com.fourth.util.GetUidUtil;
import com.fourth.vo.PayInfoVO;
import com.ljx.entity.BusinessInfo;
import com.ljx.entity.Cart;
import com.ljx.entity.Order;
import com.ljx.entity.Stock;
import com.ljx.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author Mr.ma
 * @since 2023/3/3 14:19
 **/
@RestController
@RequestMapping("/detail/orderPay")
@Api("支付操作接口")
public class UbApiOrderPayController {

    @Resource
    private UbAliPayService ubAliPayService;

    @Resource
    private UbOrderService ubOrderService;

    @Resource
    private UbBusinessInfoService ubBusinessInfoService;

    @Resource
    private UbWxPayService ubWxPayService;

    @Resource
    private UbOrderPayService ubOrderPayService;

    @Resource
    private UbCartService ubCartService;

    @Resource
    private MsgProducer msgProducer;


    /**
     * 插入一个订单，并调用支付宝服务器，然后返回相关数据
     * @param order
     * @return
     */
    @RequestMapping("buyNow")
    @ApiOperation("立即购买商品")
    @ApiImplicitParam(name = "order", value = "订单信息", dataType = "Order")
    @Transactional(rollbackFor = Exception.class)
    public Result<PayInfoVO> buyNow(@RequestBody Order order) {

        /* 判断商品库存是否充足, 充足则执行减库存操作 */
        Result result = ubAliPayService.changeStock(order.getGoodsid(), order.getNum());

        if (result.getCode() != 2000){
            return result;
        }
        /* 库存充足，生成商品订单 */
        // 获取当前登录用户的id并保存到订单中
        order.setUid(GetUidUtil.getUid());
        // 设置订单创建时间
        order.setOrderdate(new Date());
        // 设置订单code编号
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        String code = uuidStr.replace("-", "");
        order.setCode(code);
        // 设置发货状态
        order.setSend(0);
        // 设置评论状态
        order.setCommentstatus(0);
        // 设置支付状态
        order.setState(1);

        // 设置订单总价
        BigDecimal price = order.getPrice();
        BigDecimal total = price.multiply(new BigDecimal(String.valueOf(order.getNum())));
        order.setTotalmoney(total);

        // 保存到数据库中
        ubOrderService.insert(order);

        // 添加到延迟支付队列
        msgProducer.createMst(code);

        // 保存到缓存
        String orderJson = JSON.toJSONString(order);
        ubAliPayService.addRedis(order.getCode(),orderJson);

        // 拼接订单提示名，由店铺名-商品名构成
        String goodsName = ubOrderService.getGoodsName(order.getGoodsid());
        BusinessInfo businessInfo = ubBusinessInfoService.selectByBid(order.getBid());
        String bname = businessInfo.getBname();

        // 调用对应的支付方式
        PayInfoVO payInfoVO = null;
        if (order.getPaysort() == 0) {
            payInfoVO = ubWxPayService.wxPay(code, bname + "-" + goodsName, total);
        } else {
            payInfoVO = ubAliPayService.f2fPay(code, bname + "-" + goodsName, total);
        }

        if (payInfoVO != null) {
            return new Result(2000, "访问支付服务器成功", payInfoVO);
        }

        return new Result(5000, "服务器异常");
    }

    @RequestMapping("paystatus/{code}")
    @ApiOperation("查询订单支付状态")
    @ApiImplicitParam(name = "code", value = "订单信息code编号", dataType = "String")
    public Result getPayStatus(@PathVariable String code) {
        // 从缓存中获取订单信息
//        String orderJson = ubAliPayService.getRedis(code);
//        Order order = JSON.parseObject(orderJson, Order.class);
        List<Order> orderByCode = ubOrderService.getOrderByCode(code);
        if (orderByCode.get(0).getPaysort() == 0) {
            return ubWxPayService.queryPayStatus(code);
        }
        return ubAliPayService.queryPayStatus(code);
    }


    @RequestMapping("settlement")
    @ApiOperation("购物车中商品结算，获取code编号")
    @ApiImplicitParam(name = "cartList", value = "购物车结算的商品信息", dataType = "List<Cart>")
    public Result settlement(@RequestBody List<Cart> cartList){
        return ubOrderPayService.settlement(cartList);
    }

    @RequestMapping("getOderInfo")
    @ApiOperation("获取订单详细信息，主要是地址信息")
    @ApiImplicitParam(name = "code", value = "订单code编码", dataType = "String")
    public Result<List<Order>> getOderInfo(String code){
        List<Order> orderByCode = ubOrderService.getOrderByCode(code);
        return new Result(2000,"查询订单信息成功",orderByCode);
    }

    @RequestMapping("buyCart")
    @ApiOperation("购物车购买商品")
    @ApiImplicitParam(name = "order", value = "订单信息", dataType = "Order")
    @Transactional(rollbackFor = Exception.class)
    public Result buyCart(Integer paySort, @RequestBody List<Order> orders) {
        // 插入订单信息
        for (int i = 0; i < orders.size(); i++) {
            // 保存到数据库中
            ubOrderService.insert(orders.get(i));
            // 删除数据库中对应商品
            ubCartService.deleteCartByUidAndGoodsId(orders.get(i).getUid(),orders.get(i).getGoodsid());
        }

        // 添加到延迟支付队列
        msgProducer.createMst(orders.get(0).getCode());

        /* 判断库存，并执行减库存操作*/
        for (int i = 0; i < orders.size(); i++) {
            Result result = ubAliPayService.changeStock(orders.get(i).getGoodsid(), orders.get(i).getNum());
            if (result.getCode() != 2000){
                return result;
            }
        }

        // 调用对应的支付方式
        PayInfoVO payInfoVO = null;
        if (paySort == 0) {
            payInfoVO = ubWxPayService.wxPay(orders.get(0).getCode(), "菜帮帮-购物车支付", orders.get(0).getTotalmoney());
        } else {
            payInfoVO = ubAliPayService.f2fPay(orders.get(0).getCode(), "菜帮帮-购物车支付", orders.get(0).getTotalmoney());
        }

        if (payInfoVO != null) {
            return new Result(2000, "创建订单成功", payInfoVO);
        }

        return new Result(5000, "服务器异常");
    }

    @RequestMapping("payForOrder/{paySort}/{code}")
    @ApiOperation("订单中心支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paySort", value = "支付方式", dataType = "Integer"),
            @ApiImplicitParam(name = "code", value = "订单code码", dataType = "String")
    })
    public Result payForOrder(@PathVariable("paySort") Integer paySort, @PathVariable("code") String code){
        List<Order> orderByCode = ubOrderService.getOrderByCode(code);

        PayInfoVO payInfoVO = null;
        if (paySort == 0) {
            payInfoVO = ubWxPayService.wxPay(code, "菜帮帮-蔬菜", orderByCode.get(0).getTotalmoney());
        } else {
            payInfoVO = ubAliPayService.f2fPay(code, "菜帮帮-蔬菜", orderByCode.get(0).getTotalmoney());
        }

        if (payInfoVO != null) {
            return new Result(2000, "访问支付服务器成功", payInfoVO);
        }

        return new Result(5000, "服务器异常");
    }


    @RequestMapping("aliNotifyUrl")
    public String aliNotifyUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        return ubAliPayService.notifyUrl(request);
    }

    @RequestMapping("aliReturnUrl")
    public String aliReturnUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        return ubAliPayService.returnUrl(request);
    }

    @RequestMapping("wxReturnUrl")
    public String wxReturnUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        return ubAliPayService.returnUrl(request);
    }

}
